package tool

import (
	"exam_jxk/pkg/models"
	"flag"
	"fmt"
	"github.com/spf13/viper"
)

func NewConfig(path string) (*viper.Viper, error) {
	var (
		err error
		v   = viper.New()
	)
	v.AddConfigPath(".")
	v.SetConfigFile(path)
	if err = v.ReadInConfig(); err != nil {
		return nil, err
	}
	fmt.Printf("use configs file -> %s\n", v.ConfigFileUsed())
	return v, nil
}

func NewServerConfig(v *viper.Viper) (*models.ServerConfig, error) {
	var (
		err error
		o   = new(models.ServerConfig)
	)
	if err = v.UnmarshalKey("server", o); err != nil {
		return nil, err
	}
	initPort(o) // 初始化服务端口
	return o, nil
}

func initPort(conf *models.ServerConfig) {
	var servicePort *int
	if conf.ServerPort == 0 {
		servicePort = flag.Int("p", 80, "set service port")
	} else {
		servicePort = flag.Int("p", conf.ServerPort, "set service port")
	}
	conf.ServerPort = *servicePort
}
